<?php

namespace App\Exports;

use App\Enums\AssetSourceType;
use App\Models\Asset;
use App\Models\Download;
use App\Models\Product;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class AssetGiveExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;

    public function __construct(Download $data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query() // 返回的数据
    {
        return Asset::query()
            ->select('assets.*')
            ->leftJoin('frontend_users', 'frontend_users.id', 'assets.user_id')
            ->where('frontend_users.agent_id', $this->data->agent_id)
            ->where('source_type', AssetSourceType::GIVE)
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';
                $addresses = Product::query()->where('name', 'like', $likeVal)->pluck('contract_address');

                return $q->whereIn('contract_address', $addresses);
            })
            ->when(request()->start_date, function ($q) {
                return $q->where('assets.created_at', '>=', Carbon::parse(request()->start_date)->startOfDay());
            })
            ->when(request()->end_date, function ($q) {
                return $q->where('assets.created_at', '<=', Carbon::parse(request()->end_date)->endOfDay());
            })
            ->orderByDesc('assets.id')
            ->with(['user', 'product', 'giveUser']);
    }

    public function map($value): array // 指定excel中每一列的数据字段
    {
        return [
            $value['id'] ?? '',
            $value['product']->id ?? '',
            $value['product']->name ?? '',
            $value['giveUser']->user->mobile ?? '',
            $value['user']->mobile ?? '',
            $value['created_at'],
            '转赠成功',
        ];
    }

    public function headings(): array // 指定excel的表头
    {
        return [
            'ID',
            '商品ID',
            '产品名称',
            '转赠人',
            '接收人',
            '转赠时间',
            '转赠状态',
        ];
    }
}
